package jdbc;

import java.sql.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * 测试日期,取出指定时间段的数据
 */
public class Demo08 {
    /**
     * 将字符串代表的日期转为long数字(格式:yyyy-MM-dd hh:mm:ss)
     * @param dateStr
     * @return
     */
    public static long strDate(String dateStr){
        DateFormat format=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        try {
            return format.parse(dateStr).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
            return 0;
        }

    }
    public static void main(String[] args) {
        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        try {
            //加载驱动类
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc?serverTimezone=Asia/Shanghai","root","123456");
            String sql="select * from t_user where regTime>? and regTime<? order by regTime";
            ps=conn.prepareStatement(sql);
            Timestamp start=new Timestamp(strDate("2020-06-26 16:02:00"));
            System.out.println(start);
            Timestamp end=new Timestamp(strDate("2020-06-30 16:00:00"));
            ps.setObject(1,start);
            ps.setObject(2,end);

            rs=ps.executeQuery();
            while (rs.next()){
                System.out.println(rs.getInt(1)+"--"+rs.getString(2)+"--"+rs.getTimestamp(4));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (ps!=null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
